package demo16;
import java.io.*;

// 定义一个可序列化的类
class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int id;

    // 构造函数
    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    // Getter 和 Setter 方法
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Employee{name='" + name + "', id=" + id + "}";
    }
}

public class SeriallizeDemo {
    public static void main(String[] args) {
        // 创建一个 Employee 对象
        Employee employee = new Employee("John Doe", 123);

        try {
            // 序列化对象到文件
            FileOutputStream fileOut = new FileOutputStream("employee.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(employee);
            out.close();
            fileOut.close();
            System.out.println("Serialized data is saved in employee.ser");

            // 反序列化对象
            FileInputStream fileIn = new FileInputStream("employee.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            Employee deserializedEmployee = (Employee) in.readObject();
            in.close();
            fileIn.close();

            // 打印反序列化后的对象
            System.out.println("Deserialized Employee: " + deserializedEmployee);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}